/**
 * @date 2005-12-10 13:02:54
 *
 */
package org.nanhill.commons.model.table;

import java.util.ArrayList;
import java.util.List;

/**
 * @author alin
 * 
 */
public class Table {

	private String name;

	private List<Row> rows;

	public void setRows(List<Row> rows) {
		this.rows = rows;
	}

	public List<Row> getRows() {
		return rows;
	}

	public Table() {
		this(null);
	}

	public Table(String name) {
		this.rows = new ArrayList<Row>();
		this.name = name;
	}

	public Row createRow() {
		Row row = new Row();
		this.rows.add(row);
		return row;
	}

	public Row insertRow(int rowIndex) {
		Row row = new Row();
		this.rows.add(rowIndex, row);
		return row;
	}

	public Row getRow(int rowIndex) {
		return this.rows.get(rowIndex);
	}

	public Row createRow(int rowIndex) {
		Row row;
		int size = this.rows.size();
		// if row index is overflow
		if (rowIndex > size - 1) {
			// fill with null
			for (int i = size; i < rowIndex; i++) {
				this.rows.add(null);
			}
			// add a new Row in the index
			row = new Row();
			this.rows.add(row);
		} else {
			row = this.rows.get(rowIndex);
			// if the indexed row is filled with null before, replace it with a
			// new Row
			if (null == row) {
				this.rows.remove(rowIndex);
				row = new Row();
				this.rows.add(rowIndex, row);
			}
		}
		return row;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void append(Table table) {
		List<Row> addRows = table.getRows();
		for (Row row : addRows)
			this.rows.add(row);
	}

}
